#!/usr/bin/python3
# -*- coding: utf-8 -*-

import json
import re
from pathlib import Path
import jieba.posseg as pseg


def is_people_name(name):
    pair_word_list = pseg.lcut(name)
    for eve_word, cixing in pair_word_list:
        if cixing == "nr":
            return True
    return False


def is_number(num_str):
    """
    Determine whether the string can be converted to a number (int and float)
    :param num_str:
    :return:
    """
    if re.compile(r"^[-+]?[-0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$").match(num_str):
        return True
    return False


def find_files(path, pattern="*"):
    """
    Get all files under this path

    :param path: files dir
    :param pattern:
        All files are returned by default, and the file type can also be customized,
        for example: pattern="*.py"
    :return:
    """

    if not Path(path).is_dir():
        print("The path params is not dir, no files can be found!")
        return []
    for file in Path(path).rglob(pattern):
        if Path(file).is_file():
            yield str(file.resolve())


def Singleton(cls):
    """
    单例模式的装饰器实现

    Parameters
    ----------
    cls

    Returns
    -------

    """
    _instance = {}

    def _singleton(*args, **kargs):
        if cls not in _instance:
            _instance[cls] = cls(*args, **kargs)
        return _instance[cls]

    return _singleton


def read_json(path):
    with open(path, "r", encoding="utf-8") as f:
        json_dict = json.load(f)
    return json_dict


def save_json(path, d):
    with open(path, "w", encoding="utf-8") as f:
        json.dump(d, f, ensure_ascii=False)
    return True


def matching_alpha_digit(string):
    return "".join(re.findall(r"[a-zA-Z0-9]+", string))


def matching_alpha_digit_special(string):
    return "".join(re.findall(r"[a-zA-Z0-9-/]+", string))


def matching_digit(string):
    return "".join(re.findall(r"[0-9]+", string))


def matching_chinese(string):
    return "".join(re.findall(r'[\u4e00-\u9fa5]+', string))


def matching_chinese_alpha_digit_special(string):
    return "".join(re.findall(r"[\u4e00-\u9fa5a-zA-Z0-9-]+", string))
